﻿using System.Net;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;

namespace PetAdoptApi.Services.Auth;

public class AuthenticationHandlerImpl : IAuthenticationHandler

{
    public const string SchemaName = "MyAuth";

    HttpContext? _context;
    AuthenticationScheme? _scheme;

	public AuthenticationHandlerImpl()
	{
        Console.WriteLine("init AuthHandler");
	}

    public Task<AuthenticateResult> AuthenticateAsync()
    {
        var login = _context?.Request.Query["login"].FirstOrDefault();
        if (login is null) return Task.FromResult(AuthenticateResult.Fail("not authenticatd"));
        AuthenticationTicket ticket = GetTicket("name1", "role1");
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }

    private AuthenticationTicket GetTicket(string name, string role)
    {
        var cliamsIdentity = new ClaimsIdentity (new Claim[] {
            new Claim(ClaimTypes.Name,name),
            new Claim(ClaimTypes.Role,role)
        },"My_Id" );
        var principal = new ClaimsPrincipal(cliamsIdentity);
        return new AuthenticationTicket(principal, _scheme!.Name);
    }

    public Task ChallengeAsync(AuthenticationProperties? properties)
    {
        _context!.Response.StatusCode =(int) HttpStatusCode.Unauthorized;
        _context!.Response.WriteAsync("you are not Authorisze");
        return Task.CompletedTask;
    }

    public Task ForbidAsync(AuthenticationProperties? properties)
    {
        _context!.Response.StatusCode = (int) HttpStatusCode.Forbidden;
        return Task.CompletedTask;
    }

    public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
    {
        _context = context;
        _scheme = scheme;
        return Task.CompletedTask;
    }
}

